#include "threadPool.h"

/* Usage:  */
// 连接池初始化
int mysql_pool_init(ConnectionPool_t *pool, const char *host, const char *user, const char *password, const char *db, unsigned int port){
    strncpy(pool->host,host,sizeof(pool->host));
    strncpy(pool->user,user,sizeof(pool->user));
    strncpy(pool->password,password,sizeof(pool->password));
    strncpy(pool->db,db,sizeof(pool->db));
    pool->port = port;
    int i;
    pthread_mutex_init(&pool->lock,NULL);
    for( i = 0; i < POOL_SIZE; i++){
        pool->pool[i].conn = mysql_init(NULL); // 初始化数据库连接，默认填写NULL
        if(!mysql_real_connect(pool->pool[i].conn,host,user,password,db,3306,NULL,0)){
            fprintf(stderr,"Mysql connect failed:%s!\n",mysql_error(NULL));
            return -1;
        }
        pool->pool[i].is_use = 0; // 将当前池里的数据库设置为空闲
    }
    return 0;
}
// 获取一个连接
int mysql_pool_get(ConnectionPool_t *pool,MYSQL **recvPool){
    pthread_mutex_lock(&pool->lock);
    for(int i = 0; i < POOL_SIZE; i++){
        if(!pool->pool[i].is_use){
            pool->pool[i].is_use = 1;
            *recvPool = pool->pool[i].conn;
            pthread_mutex_unlock(&pool->lock);
            return 0;
        }
    }
    pthread_mutex_unlock(&pool->lock);
    *recvPool = NULL;
    return -1;
}
// 释放连接
int freeConn(ConnectionPool_t *pool,MYSQL *conn){
    pthread_mutex_lock(&pool->lock);
    for(int i = 0; i < POOL_SIZE; i++){
        if(pool->pool[i].conn == conn){
            
            pool->pool[i].is_use = 0;
            pthread_mutex_unlock(&pool->lock);
            return 0;
        }
    }
    pthread_mutex_unlock(&pool->lock);
    return -1;
}
//销毁池
int destroyPool(ConnectionPool_t *pool) {
    for (int i = 0; i < POOL_SIZE; ++i) {
        if (pool->pool[i].conn) {
            mysql_close(pool->pool[i].conn);
            pool->pool[i].conn = NULL;
        }
    }
    int ret = pthread_mutex_destroy(&pool->lock);
    if (ret != 0) {
        // 可在此处记录日志或错误处理
        return -1; // 标记为失败
    }
    return 0; // 成功
}
